<template>
  <div class="network-topology-interaction">
    <!-- 交互工具栏 -->
    <a-card size="small" class="interaction-toolbar">
      <template #title>
        <a-space>
          <interaction-outlined />
          交互工具
        </a-space>
      </template>
      
      <a-space wrap>
        <!-- 选择模式 -->
        <a-button-group>
          <a-tooltip title="选择模式">
            <a-button 
              :type="interactionMode === 'select' ? 'primary' : 'default'"
              size="small"
              @click="setInteractionMode('select')"
            >
              <template #icon><select-outlined /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip title="拖拽模式">
            <a-button 
              :type="interactionMode === 'drag' ? 'primary' : 'default'"
              size="small"
              @click="setInteractionMode('drag')"
            >
              <template #icon><drag-outlined /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip title="缩放模式">
            <a-button 
              :type="interactionMode === 'zoom' ? 'primary' : 'default'"
              size="small"
              @click="setInteractionMode('zoom')"
            >
              <template #icon><zoom-in-outlined /></template>
            </a-button>
          </a-tooltip>
        </a-button-group>

        <!-- 视图控制 -->
        <a-button-group>
          <a-tooltip title="放大">
            <a-button size="small" @click="zoomIn">
              <template #icon><plus-outlined /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip title="缩小">
            <a-button size="small" @click="zoomOut">
              <template #icon><minus-outlined /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip title="适应画布">
            <a-button size="small" @click="fitView">
              <template #icon><fullscreen-outlined /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip title="重置视图">
            <a-button size="small" @click="resetView">
              <template #icon><reload-outlined /></template>
            </a-button>
          </a-tooltip>
        </a-button-group>

        <!-- 高级功能 -->
        <a-button-group>
          <a-tooltip title="高亮路径">
            <a-button 
              :type="highlightMode ? 'primary' : 'default'"
              size="small"
              @click="toggleHighlightMode"
            >
              <template #icon><highlight-outlined /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip title="聚焦模式">
            <a-button 
              :type="focusMode ? 'primary' : 'default'"
              size="small"
              @click="toggleFocusMode"
            >
              <template #icon><eye-outlined /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip title="动画播放">
            <a-button 
              :type="animationPlaying ? 'primary' : 'default'"
              size="small"
              @click="toggleAnimation"
            >
              <template #icon><play-circle-outlined v-if="!animationPlaying" /><pause-circle-outlined v-else /></template>
            </a-button>
          </a-tooltip>
        </a-button-group>
      </a-space>
    </a-card>

    <!-- 选择信息面板 -->
    <a-card v-if="selectedNodes.length > 0 || selectedEdges.length > 0" size="small" class="selection-panel">
      <template #title>
        <a-space>
          <info-circle-outlined />
          选择信息
          <a-button size="small" type="text" @click="clearSelection">
            <template #icon><close-outlined /></template>
          </a-button>
        </a-space>
      </template>
      
      <!-- 选中的节点 -->
      <div v-if="selectedNodes.length > 0" class="selection-section">
        <h4>选中节点 ({{ selectedNodes.length }})</h4>
        <div class="selected-items">
          <a-tag
            v-for="node in selectedNodes"
            :key="node.id"
            :color="getNodeTypeColor(node.type)"
            closable
            @close="removeNodeFromSelection(node.id)"
          >
            {{ node.name }}
          </a-tag>
        </div>
      </div>

      <!-- 选中的边 -->
      <div v-if="selectedEdges.length > 0" class="selection-section">
        <h4>选中关系 ({{ selectedEdges.length }})</h4>
        <div class="selected-items">
          <a-tag
            v-for="edge in selectedEdges"
            :key="edge.id"
            :color="getEdgeTypeColor(edge.type)"
            closable
            @close="removeEdgeFromSelection(edge.id)"
          >
            {{ getEdgeLabel(edge) }}
          </a-tag>
        </div>
      </div>

      <!-- 批量操作 -->
      <div class="batch-operations">
        <a-space>
          <a-button size="small" @click="highlightSelection">
            <template #icon><highlight-outlined /></template>
            高亮选中
          </a-button>
          <a-button size="small" @click="hideSelection">
            <template #icon><eye-invisible-outlined /></template>
            隐藏选中
          </a-button>
          <a-button size="small" @click="exportSelection">
            <template #icon><download-outlined /></template>
            导出选中
          </a-button>
        </a-space>
      </div>
    </a-card>

    <!-- 路径分析面板 -->
    <a-card v-if="pathAnalysisVisible" size="small" class="path-analysis-panel">
      <template #title>
        <a-space>
          <route-outlined />
          路径分析
          <a-button size="small" type="text" @click="closePathAnalysis">
            <template #icon><close-outlined /></template>
          </a-button>
        </a-space>
      </template>
      
      <div class="path-finder">
        <a-row :gutter="8">
          <a-col :span="10">
            <a-select
              v-model:value="pathAnalysis.sourceNode"
              placeholder="起始节点"
              size="small"
              show-search
              :filter-option="filterNodeOption"
              style="width: 100%"
            >
              <a-select-option
                v-for="node in availableNodes"
                :key="node.id"
                :value="node.id"
              >
                {{ node.name }}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :span="10">
            <a-select
              v-model:value="pathAnalysis.targetNode"
              placeholder="目标节点"
              size="small"
              show-search
              :filter-option="filterNodeOption"
              style="width: 100%"
            >
              <a-select-option
                v-for="node in availableNodes"
                :key="node.id"
                :value="node.id"
              >
                {{ node.name }}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :span="4">
            <a-button 
              size="small" 
              type="primary" 
              @click="findPath"
              :loading="pathFinding"
              style="width: 100%"
            >
              查找
            </a-button>
          </a-col>
        </a-row>
      </div>

      <!-- 路径结果 -->
      <div v-if="pathAnalysis.paths.length > 0" class="path-results">
        <h4>找到 {{ pathAnalysis.paths.length }} 条路径</h4>
        <div class="path-list">
          <div
            v-for="(path, index) in pathAnalysis.paths"
            :key="index"
            class="path-item"
            :class="{ active: pathAnalysis.selectedPath === index }"
            @click="selectPath(index)"
          >
            <div class="path-header">
              <span>路径 {{ index + 1 }}</span>
              <a-tag size="small">{{ path.length }} 步</a-tag>
            </div>
            <div class="path-nodes">
              <span
                v-for="(nodeId, nodeIndex) in path"
                :key="nodeId"
                class="path-node"
              >
                {{ getNodeName(nodeId) }}
                <arrow-right-outlined v-if="nodeIndex < path.length - 1" />
              </span>
            </div>
          </div>
        </div>
      </div>
    </a-card>

    <!-- 网络分析面板 -->
    <a-card v-if="analysisVisible" size="small" class="analysis-panel">
      <template #title>
        <a-space>
          <fund-outlined />
          网络分析
          <a-button size="small" type="text" @click="closeAnalysis">
            <template #icon><close-outlined /></template>
          </a-button>
        </a-space>
      </template>
      
      <a-tabs size="small" v-model:activeKey="analysisTab">
        <a-tab-pane key="centrality" tab="中心性分析">
          <div class="centrality-analysis">
            <a-select
              v-model:value="centralityType"
              size="small"
              style="width: 100%; margin-bottom: 8px"
              @change="calculateCentrality"
            >
              <a-select-option value="degree">度中心性</a-select-option>
              <a-select-option value="betweenness">介数中心性</a-select-option>
              <a-select-option value="closeness">接近中心性</a-select-option>
              <a-select-option value="eigenvector">特征向量中心性</a-select-option>
            </a-select>
            
            <div class="centrality-results">
              <div
                v-for="result in centralityResults"
                :key="result.nodeId"
                class="centrality-item"
              >
                <span class="node-name">{{ result.nodeName }}</span>
                <a-progress
                  :percent="result.value * 100"
                  size="small"
                  :show-info="false"
                />
                <span class="centrality-value">{{ result.value.toFixed(3) }}</span>
              </div>
            </div>
          </div>
        </a-tab-pane>
        
        <a-tab-pane key="community" tab="社区检测">
          <div class="community-analysis">
            <a-button 
              size="small" 
              type="primary" 
              @click="detectCommunities"
              :loading="communityDetecting"
              style="width: 100%; margin-bottom: 8px"
            >
              检测社区
            </a-button>
            
            <div v-if="communityResults.length > 0" class="community-results">
              <div
                v-for="community in communityResults"
                :key="community.id"
                class="community-item"
              >
                <div class="community-header">
                  <a-tag :color="community.color">
                    社区 {{ community.id }}
                  </a-tag>
                  <span>{{ community.nodes.length }} 个节点</span>
                </div>
                <div class="community-nodes">
                  <a-tag
                    v-for="nodeId in community.nodes"
                    :key="nodeId"
                    size="small"
                  >
                    {{ getNodeName(nodeId) }}
                  </a-tag>
                </div>
              </div>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import {
  InteractionOutlined,
  SelectOutlined,
  DragOutlined,
  ZoomInOutlined,
  PlusOutlined,
  MinusOutlined,
  FullscreenOutlined,
  ReloadOutlined,
  HighlightOutlined,
  EyeOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  InfoCircleOutlined,
  CloseOutlined,
  EyeInvisibleOutlined,
  DownloadOutlined,
  RouteOutlined,
  ArrowRightOutlined,
  FundOutlined
} from '@ant-design/icons-vue'
import type { NetworkVisualizationData, NetworkNode, NetworkEdge } from '@/api/types'

interface Props {
  data: NetworkVisualizationData
  graphRef?: any
}

interface Emits {
  (e: 'interactionModeChange', mode: string): void
  (e: 'selectionChange', selection: { nodes: NetworkNode[], edges: NetworkEdge[] }): void
  (e: 'pathHighlight', path: string[]): void
  (e: 'communityHighlight', communities: any[]): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const interactionMode = ref('select')
const highlightMode = ref(false)
const focusMode = ref(false)
const animationPlaying = ref(false)

// 选择状态
const selectedNodes = ref<NetworkNode[]>([])
const selectedEdges = ref<NetworkEdge[]>([])

// 路径分析
const pathAnalysisVisible = ref(false)
const pathFinding = ref(false)
const pathAnalysis = ref({
  sourceNode: '',
  targetNode: '',
  paths: [] as string[][],
  selectedPath: -1
})

// 网络分析
const analysisVisible = ref(false)
const analysisTab = ref('centrality')
const centralityType = ref('degree')
const centralityResults = ref<any[]>([])
const communityDetecting = ref(false)
const communityResults = ref<any[]>([])

// 计算属性
const availableNodes = computed(() => props.data.nodes || [])

// 方法
const setInteractionMode = (mode: string) => {
  interactionMode.value = mode
  emit('interactionModeChange', mode)
  message.info(`切换到${getInteractionModeLabel(mode)}模式`)
}

const getInteractionModeLabel = (mode: string): string => {
  const labels: Record<string, string> = {
    select: '选择',
    drag: '拖拽',
    zoom: '缩放'
  }
  return labels[mode] || mode
}

// 视图控制
const zoomIn = () => {
  props.graphRef?.zoomIn?.()
}

const zoomOut = () => {
  props.graphRef?.zoomOut?.()
}

const fitView = () => {
  props.graphRef?.fitView?.()
}

const resetView = () => {
  props.graphRef?.fitView?.()
  clearSelection()
  message.success('视图已重置')
}

// 高级功能
const toggleHighlightMode = () => {
  highlightMode.value = !highlightMode.value
  message.info(highlightMode.value ? '开启高亮模式' : '关闭高亮模式')
}

const toggleFocusMode = () => {
  focusMode.value = !focusMode.value
  message.info(focusMode.value ? '开启聚焦模式' : '关闭聚焦模式')
}

const toggleAnimation = () => {
  animationPlaying.value = !animationPlaying.value
  message.info(animationPlaying.value ? '开始动画播放' : '停止动画播放')
}

// 选择管理
const clearSelection = () => {
  selectedNodes.value = []
  selectedEdges.value = []
  emit('selectionChange', { nodes: [], edges: [] })
}

const removeNodeFromSelection = (nodeId: string) => {
  selectedNodes.value = selectedNodes.value.filter(n => n.id !== nodeId)
  emit('selectionChange', { nodes: selectedNodes.value, edges: selectedEdges.value })
}

const removeEdgeFromSelection = (edgeId: string) => {
  selectedEdges.value = selectedEdges.value.filter(e => e.id !== edgeId)
  emit('selectionChange', { nodes: selectedNodes.value, edges: selectedEdges.value })
}

const highlightSelection = () => {
  // 实现高亮选中项的逻辑
  message.success('已高亮选中项')
}

const hideSelection = () => {
  // 实现隐藏选中项的逻辑
  message.success('已隐藏选中项')
}

const exportSelection = () => {
  const selectionData = {
    nodes: selectedNodes.value,
    edges: selectedEdges.value,
    timestamp: new Date().toISOString()
  }
  
  const dataStr = JSON.stringify(selectionData, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)
  const link = document.createElement('a')
  link.href = url
  link.download = `selection-${Date.now()}.json`
  link.click()
  URL.revokeObjectURL(url)
  
  message.success('选中项已导出')
}

// 路径分析
const openPathAnalysis = () => {
  pathAnalysisVisible.value = true
}

const closePathAnalysis = () => {
  pathAnalysisVisible.value = false
  pathAnalysis.value = {
    sourceNode: '',
    targetNode: '',
    paths: [],
    selectedPath: -1
  }
}

const findPath = async () => {
  if (!pathAnalysis.value.sourceNode || !pathAnalysis.value.targetNode) {
    message.warning('请选择起始节点和目标节点')
    return
  }
  
  pathFinding.value = true
  
  try {
    // 模拟路径查找算法
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 生成模拟路径
    const paths = generateMockPaths(
      pathAnalysis.value.sourceNode,
      pathAnalysis.value.targetNode
    )
    
    pathAnalysis.value.paths = paths
    message.success(`找到 ${paths.length} 条路径`)
  } catch (error) {
    message.error('路径查找失败')
  } finally {
    pathFinding.value = false
  }
}

const selectPath = (index: number) => {
  pathAnalysis.value.selectedPath = index
  const path = pathAnalysis.value.paths[index]
  emit('pathHighlight', path)
  message.info(`已选择路径 ${index + 1}`)
}

const generateMockPaths = (source: string, target: string): string[][] => {
  // 简单的模拟路径生成
  const intermediateNodes = availableNodes.value
    .filter(n => n.id !== source && n.id !== target)
    .slice(0, 3)
  
  const paths: string[][] = []
  
  // 直接路径
  paths.push([source, target])
  
  // 通过中间节点的路径
  intermediateNodes.forEach(node => {
    paths.push([source, node.id, target])
  })
  
  return paths
}

// 网络分析
const openAnalysis = () => {
  analysisVisible.value = true
}

const closeAnalysis = () => {
  analysisVisible.value = false
}

const calculateCentrality = async () => {
  try {
    // 模拟中心性计算
    await new Promise(resolve => setTimeout(resolve, 500))
    
    centralityResults.value = availableNodes.value
      .slice(0, 10)
      .map(node => ({
        nodeId: node.id,
        nodeName: node.name,
        value: Math.random()
      }))
      .sort((a, b) => b.value - a.value)
    
    message.success(`${getCentralityTypeLabel(centralityType.value)}计算完成`)
  } catch (error) {
    message.error('中心性计算失败')
  }
}

const getCentralityTypeLabel = (type: string): string => {
  const labels: Record<string, string> = {
    degree: '度中心性',
    betweenness: '介数中心性',
    closeness: '接近中心性',
    eigenvector: '特征向量中心性'
  }
  return labels[type] || type
}

const detectCommunities = async () => {
  communityDetecting.value = true
  
  try {
    // 模拟社区检测
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    const colors = ['#1890ff', '#52c41a', '#722ed1', '#fa8c16', '#eb2f96']
    const communityCount = Math.min(5, Math.max(2, Math.floor(availableNodes.value.length / 5)))
    
    communityResults.value = Array.from({ length: communityCount }, (_, i) => ({
      id: i + 1,
      color: colors[i % colors.length],
      nodes: availableNodes.value
        .slice(i * Math.floor(availableNodes.value.length / communityCount), 
               (i + 1) * Math.floor(availableNodes.value.length / communityCount))
        .map(n => n.id)
    }))
    
    emit('communityHighlight', communityResults.value)
    message.success(`检测到 ${communityCount} 个社区`)
  } catch (error) {
    message.error('社区检测失败')
  } finally {
    communityDetecting.value = false
  }
}

// 辅助函数
const getNodeTypeColor = (type: string): string => {
  const colors: Record<string, string> = {
    CORPORATE: '#1890ff',
    URBAN: '#52c41a',
    CONCEPTUAL: '#722ed1',
    INDIVIDUAL: '#fa8c16',
    HYBRID: '#eb2f96',
    SYSTEM: '#13c2c2'
  }
  return colors[type] || '#666'
}

const getEdgeTypeColor = (type: string): string => {
  const colors: Record<string, string> = {
    COLLABORATION: '#52c41a',
    COMPETITION: '#f5222d',
    DEPENDENCY: '#1890ff',
    FUSION: '#722ed1',
    COMMUNICATION: '#fa8c16',
    INHERITANCE: '#13c2c2'
  }
  return colors[type] || '#666'
}

const getEdgeLabel = (edge: NetworkEdge): string => {
  const sourceNode = availableNodes.value.find(n => n.id === edge.source)
  const targetNode = availableNodes.value.find(n => n.id === edge.target)
  return `${sourceNode?.name || edge.source} → ${targetNode?.name || edge.target}`
}

const getNodeName = (nodeId: string): string => {
  const node = availableNodes.value.find(n => n.id === nodeId)
  return node?.name || nodeId
}

const filterNodeOption = (input: string, option: any) => {
  return option.children.toLowerCase().includes(input.toLowerCase())
}

// 暴露方法
defineExpose({
  openPathAnalysis,
  openAnalysis,
  clearSelection,
  setInteractionMode
})
</script>

<style scoped>
.network-topology-interaction {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.interaction-toolbar,
.selection-panel,
.path-analysis-panel,
.analysis-panel {
  flex-shrink: 0;
}

.selection-section {
  margin-bottom: 12px;
}

.selection-section h4 {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #666;
}

.selected-items {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
}

.batch-operations {
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.path-finder {
  margin-bottom: 12px;
}

.path-results {
  margin-top: 12px;
}

.path-results h4 {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #666;
}

.path-list {
  max-height: 200px;
  overflow-y: auto;
}

.path-item {
  padding: 8px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-bottom: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.path-item:hover {
  border-color: #1890ff;
}

.path-item.active {
  border-color: #1890ff;
  background-color: #f6ffed;
}

.path-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
  font-size: 12px;
  font-weight: 500;
}

.path-nodes {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  color: #666;
}

.path-node {
  display: flex;
  align-items: center;
  gap: 2px;
}

.centrality-analysis,
.community-analysis {
  max-height: 300px;
  overflow-y: auto;
}

.centrality-results {
  margin-top: 8px;
}

.centrality-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
  font-size: 11px;
}

.node-name {
  flex: 0 0 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.centrality-value {
  flex: 0 0 40px;
  text-align: right;
  color: #666;
}

.community-results {
  margin-top: 8px;
}

.community-item {
  margin-bottom: 12px;
  padding: 8px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
}

.community-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
}

.community-nodes {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

:deep(.ant-card-head-title) {
  font-size: 14px;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-progress-inner) {
  height: 4px;
}

@media (max-width: 768px) {
  .network-topology-interaction {
    gap: 8px;
  }
  
  .path-list {
    max-height: 150px;
  }
  
  .centrality-analysis,
  .community-analysis {
    max-height: 200px;
  }
}
</style>